package com.ohuang.wallpapermanager.screen

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContract
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.ohuang.wallpapermanager.WallPaperManager
import com.ohuang.wallpapermanager.compose.dp2sp
import com.ohuang.wallpapermanager.compose.getContext
import com.ohuang.wallpapermanager.compose.onClickSafe
import com.ohuang.wallpapermanager.compose.rememberUriPainter
import com.ohuang.wallpapermanager.compose.rememberUriPainterSafe
import com.ohuang.wallpapermanager.util.PermissionUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

@Composable
fun SettingWallPaperScreen(isLockWall: Boolean, goBack: () -> Unit) {

    Column(modifier = Modifier.fillMaxWidth()) {
        TopBar(title = "设置${if (isLockWall) "锁屏" else "桌面"}壁纸", backClick = goBack)
        SettingWallPaperScreenImpl(isLockWall, goBack)
    }
}

@Preview(backgroundColor = 0xffffffff, showBackground = true)
@Composable
private fun SettingWallPaperScreenShow() {
    SettingWallPaperScreen(true) { }
}

@Composable
private fun SettingWallPaperScreenImpl(isLockWall: Boolean, goBack: () -> Unit) {
    var imageUri by remember {
        mutableStateOf("")
    }
    val buttonEnable = remember {
        mutableStateOf(true)
    }
    val context = getContext()
    Column(modifier = Modifier.verticalScroll(rememberScrollState())) {

        val rememberLauncherForActivityResult =
            rememberLauncherForActivityResult(
                contract = getImageActivityResultContract(),
                onResult = {
                    if (it != null) {
                        imageUri = it.toString()
                    }
                })

        if (imageUri.isNotEmpty()) {
            SettingButton(buttonEnable, context, imageUri, isLockWall, goBack)
        }

        Box(modifier = Modifier
            .fillMaxWidth()
            .heightIn(min = 200.dp)
            .padding(10.dp)
            .onClickSafe(enabled = buttonEnable.value) {
                rememberLauncherForActivityResult.launch(true)
            }) {

            if (imageUri.isEmpty()) {
                Text(
                    modifier = Modifier.align(Alignment.Center),
                    text = "点击选择图片",
                    fontSize = 16.dp2sp()
                )
            } else {
                Image(
                    modifier = Modifier
                        .align(Alignment.Center)
                        .clip(shape = RoundedCornerShape(10.dp)),
                    painter = rememberUriPainterSafe(Uri.parse(imageUri)),
                    contentDescription = ""
                )
            }
        }

        Spacer(modifier = Modifier.height(40.dp))


    }
}

@Composable
private fun SettingButton(
    buttonEnable: MutableState<Boolean>,
    context: Context,
    imageUri: String,
    isLockWall: Boolean,
    goBack: () -> Unit
) {
    val rememberCoroutineScope = rememberCoroutineScope()
    Box(modifier = Modifier.fillMaxWidth()) {
        Button(
            enabled = buttonEnable.value,
            modifier = Modifier.align(Alignment.Center), onClick = {
                val checkAndRequest = PermissionUtil.checkAndRequest(
                    context as Activity,
                    arrayListOf("android.permission.SET_WALLPAPER")
                )
                if (!checkAndRequest) {
                    return@Button
                }
                buttonEnable.value = false
                rememberCoroutineScope.launch(Dispatchers.IO) {
                    WallPaperManager.setWallPaperForUri(
                        Uri.parse(imageUri),
                        context,
                        isLockWall
                    )
                    withContext(Dispatchers.Main) {
                        goBack()
                    }
                }

            }) {
            Text("设置${if (isLockWall) "锁屏" else "桌面"}壁纸")
        }
    }
}



fun getImageActivityResultContract(): ActivityResultContract<Boolean, Uri?> {
    return object :
        ActivityResultContract<Boolean, Uri?>() {
        override fun createIntent(context: Context, input: Boolean): Intent {
            val intent = Intent(Intent.ACTION_GET_CONTENT)
            intent.type = "image/*"
            return intent
        }

        override fun parseResult(resultCode: Int, intent: Intent?): Uri? {
            return intent?.data
        }
    }
}


